package edu.neu.highway.neo4j;

import org.neo4j.driver.*;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.util.List;
import java.util.function.Function;

import static org.neo4j.driver.Values.parameters;

@Component
public class CypherExecutor implements Closeable {
    private final Driver driver;

    public CypherExecutor() {
        this.driver = GraphDatabase.driver(
                "bolt://192.168.44.100:7687",
                AuthTokens.basic("neo4j", "WangY20010418")
        );
    }

    public <T> List<T> readCyphers(String cypher, Function<Record, T> mapper) {
        try (Session session = driver.session()) {
            return session.readTransaction(tx -> tx.run(cypher).list(mapper));
        }
    }

    public void writeCyphers(String cypher, Object... params) {
        try(Session session = driver.session()) {
            session.writeTransaction(tx -> tx.run(cypher, parameters(params)));
        }
    }

    @Override
    public void close() {
        driver.close();
    }
}
